package com.gvsoft.communication.net.bufferpool;

import com.gvsoft.communication.common.Config;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.nio.ByteBuffer;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * Created with IntelliJ IDEA.
 * ProjectName:gvMsgRouting
 * Author: zhaoqiubo
 * Date: 15/9/2
 * Time: 下午3:04
 * Desc: 读缓冲池
 */
public class ReadBufferPool {

    private final static Logger logger = LogManager.getLogger("net");

    /**
     * 用于读的bytebuffer的大小设置
     */
    private static Integer block;

    /**
     * 已使用的bytebuffer数量
     */
    private final static AtomicInteger usedCount = new AtomicInteger(0);
    private final static LinkedBlockingQueue<ByteBuffer> bufferQ = new LinkedBlockingQueue<>();

    static {
        Integer poolSize = Config.getReadBufferPoolSize();
        block = Config.getReadBlock();
        logger.info("初始化读取消息缓冲区数量为:"+poolSize+",每个缓冲区大小为:"+block);
        for (int i = 0; i < poolSize; i++) {
            ByteBuffer byteBuffer = ByteBuffer.allocate(block);
            bufferQ.offer(byteBuffer);

        }
    }

    public static ByteBuffer getBuffer() {

        ByteBuffer byteBuffer = bufferQ.poll();
        if (byteBuffer != null) {
            usedCount.incrementAndGet();
            return byteBuffer;
        } else {
            logger.info("服务端读缓冲池已经用尽，请考虑增加缓冲区配置！");
            return ByteBuffer.allocate(block);
        }

    }

    public static void freeBuffer(ByteBuffer byteBuffer) {

        bufferQ.offer(byteBuffer);
        usedCount.decrementAndGet();

    }
}
